#include <device.h>
#include <klibc/malloc.h>
#include <driver.h>
#include <klibc/string.h>
#include <config.h>
#include <klibc/stdio.h>

/* dev init */
int
dev_init()
{
	devlist = NULL;
	
	return 0;
}

/* probe all devices and add them in the list */
int
dev_probe()
{
	#ifdef NO_DEV
		return 0;
	#endif
	
	int num = 0;

	/* empty the list */
	dev_t *dev = devlist;
	
	if(dev != NULL)
	{
		dev_t *n = NULL;
		while(dev != NULL)
		{
			n = dev->next;
			free(dev);
			dev = n;			
		}		
	}
	
	/* probe all drivers */
	drv_t *d = drvlist;
	
	while(d != NULL)
	{
		int v = 0;
		
		if(d->probe == NULL)
		{
			d = d->next;
			continue;
		}
		v = d->probe();
		//printf("added %s\n", d->name);
		
		if(v != 0)
		{
			/* add the device in the list */
			dev_t *dv = (dev_t *) malloc(sizeof(dev_t));
			dv->drv = d;
			dv->next = devlist;
			devlist = dv;
			
			/* modify device */
			strcpy(dv->name, d->name);
			strcat(dv->name, "0");
			
			if(d->init != NULL)
				d->init();
			num++;
		}
		d = d->next;
	}
	
	return num;	
}

/* get the i device */
dev_t *
dev_iget(int i)
{
	#ifdef NO_DEV
		return (dev_t *) NULL;
	#endif
	
	dev_t *d = devlist;
	int j = 0;
	
	while(d != NULL)
	{
		if(i == j)
			return d;
			
		j++;
		d = d->next;
	}
	return NULL;	
}


/* read a device from list */
int
dev_readdir(int i, struct dirent_t *entry)
{
	#ifdef NO_DEV
		return -1;
	#endif
	
	
	dev_t *d = devlist;
	int j = 0;
	
	while(d != NULL)
	{
		if(i == j)
		{
			strcpy(entry->name, d->name);
			entry->inode_n = i;
			return 0;
		}
		
		j++;
		d = d->next;
	}
	return -1;
}
